const {src , dest , parallel , series , watch}  = require("gulp")

const del = require("del")

const browserSync  = require('browser-sync')

const plugins = require("gulp-load-plugins")()

const sass = require('gulp-sass')

const bs = browserSync.create()//创建服务器


//清除文件
const clean  = ()=>{
    return del(['tem','dist'])
}

//对scss文件进行处理
const style = ()=>{
    return src("src/assets/styles/*.scss",{base:"src"})
    .pipe(sass({outputStyle: 'expanded'} ))//大括号展开
    .pipe(dest('tem'))
    .pipe(bs.reload({stream:true}))//以流的方式推到服务器
}

//对js进行文件处理
const script = ()=>{
  return src("src/assets/scripts/*.js",{base:"src"})
  .pipe(plugins.babel({ presets: [require('@babel/preset-env')]  }))
  .pipe(dest('tem'))
}


//对html进行文件处理
const page = ()=>{
  return src('src/*.html',{base:"src"})
  .pipe(plugins.swig())
  .pipe(dest("tem"))
}

//对img进行处理
const image = ()=>{
   return src("src/assets/images/**",{base:"src"})
   .pipe(plugins.imagemin())
   .pipe(dest('tem'))
}

//服务器配置
const serve = ()=>{
  watch('src/*.html',page)
  watch('src/assets/styles/*.scss',style)
  watch('src/assets/scripts/*.js',script)
  watch(['src/assets/images/**'],bs.reload)//修改后自动更新浏览器   
  bs.init({
    notify:false,
    port:8080,
    files:'tem/**',
    server:{
      baseDir:['tem',"src"],
      routes:{
        "/node_modules":"node_modules"
      }
    }
  })
}
//对文件进行压缩操作 
 const useref = ()=>{
   return src('tem/*.html', { base: 'tem' })
   .pipe(plugins.useref({searchPath:['tem',"."]}))//指定找到的文件
   .pipe(plugins.if(/\.js$/,plugins.uglify()))
   .pipe(plugins.if(/\.css$/,plugins.cleanCss()))
   .pipe(plugins.if(/\.html$/,plugins.htmlmin({
    collapseWhitespace: true,//去掉空白字符
    minifyCSS: true,//压缩css
    minifyJS: true //压缩js
   })))
   .pipe(dest('dist'))
 }
//这里我只写了一种命令 可以根据不同场景添加命令
const build = series(clean,series(parallel(style,script,page,image),useref))

module.exports = {
  build,
  serve,
}